package com.yonyou.pmclouds.personnel.process;

import com.yonyou.pmclouds.basecom.bp.processor.MultiProcessor;
import com.yonyou.pmclouds.basecom.bp.processor.SingleProcessor;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.personnel.entity.PersonnelVO;
import org.apache.commons.lang.StringUtils;
import java.util.regex.Pattern;

/**
 * @Author chulf
 * @Date 2020/4/15
 * @Description 校验
 **/
public class PhoneAndEmailCheckBeforeProcess implements MultiProcessor<PersonnelVO>, SingleProcessor<PersonnelVO> {

    private static final String REGEX_MOBILE ="((\\+86|0086)?\\s*)((134[0-8]\\d{7})|(((13([0-3]|[5-9]))|(14[5-9])|15([0-3]|[5-9])|(16(2|[5-7]))|17([0-3]|[5-8])|18[0-9]|19(1|[8-9]))\\d{8})|(14(0|1|4)0\\d{7})|(1740([0-5]|[6-9]|[10-12])\\d{7}))";

    private static final String REGEX_EMAIL = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";

    @Override
    public void process(PersonnelVO[] vos, PersonnelVO[] origs) throws BusinessException {

        for (PersonnelVO vo : vos) {
            if (StringUtils.isEmpty(vo.getPhone()) && StringUtils.isEmpty(vo.getEmail())) throw new BusinessException("手机号或邮箱必填一个！");
            if (!isMobile(vo.getPhone()) && !isEmail(vo.getEmail())) throw new BusinessException("请输入正确的手机号或邮箱!");
        }
    }

    @Override
    public void process(PersonnelVO vo, PersonnelVO orig) throws BusinessException {
        if(StringUtils.isEmpty(vo.getPhone()) && StringUtils.isEmpty(vo.getEmail())) throw new BusinessException("手机号或邮箱必填一个！");
        if (!isMobile(vo.getPhone()) && !isEmail(vo.getEmail())) throw new BusinessException("请输入正确的手机号或邮箱!");
    }


    /**
     * 判断是否是手机号
     * @param tel 手机号
     * @return boolean true:是  false:否
     */
    public static boolean isMobile(String tel) {
        if (StringUtils.isEmpty(tel)){ return false;}
        return Pattern.matches(REGEX_MOBILE, tel);
    }

    /**
     *
     * @param email
     * @return 判断是否是邮箱
     */
    public static boolean isEmail(String email){
        if (StringUtils.isEmpty(email)) return false;
        return Pattern.matches(REGEX_EMAIL,email);
    }
}
